import "./index.less";
import { BasicForm, useForm } from "@/components/Form";
import { BasicTable, useTable, BasicColumn, FormSchema } from "@/components/Table";
import Toolbar from "@/components/ViewComponents/Toolbar";
import { healthCheckPatientGet, healthCheckPatientUpdate } from "@/api/MedicalExamination";
import { useTranslation } from "react-i18next";
import { message, Tag, Tree } from "antd";
import { useState } from "react";
import PatientInformation from "@/components/ViewComponents/PatientInformation/index";
import type { DataNode, TreeProps } from "antd/es/tree";
import { IconEnum } from "@/enums/appEnum";
import Icon from "@/components/Icon";
export default function general_health() {
	const { t } = useTranslation();
	let [userList, setUserList] = useState({
		patientCond: [{}],
		patientFams: [{}],
		patDiseases: [],
		patientInsur: {},
		patientJobs: {},
		services: {}
	});
	let saveList: any = {
		services: {}
	};
	let [treeData, setSreeData] = useState<DataNode[]>();

	const leftTableColumns: BasicColumn[] = [
		{
			title: t("felix_ui.sq_numb"),
			dataIndex: "sq_numb",
			render: (text, record, index) => index * 1 + 1 // 设置序号
		},
		{
			title: t("felix_ui.med_history"),
			dataIndex: "diseaseName"
		},
		{
			title: t("felix_ui.yes_no"),
			dataIndex: "status",
			render: (text, record) => {
				return record.status === "1" ? <Tag color="success">Finished</Tag> : <Tag color="error">UnFinished</Tag>;
			}
		},
		{
			title: t("felix_ui.explanation"),
			dataIndex: "description"
		}
	];
	const [leftTable] = useTable({
		dataSource: userList.patDiseases,
		columns: leftTableColumns,
		pagination: false,
		maxHeight: 200
	});
	const examinationOptions = [
		{ label: "UnExamined", value: "0" },
		{ label: "Examined", value: "1" },
		{ label: "Canceled", value: "2" }
	];
	const healthyOptions = [
		{ label: "Healthy", value: 1 },
		{ label: "Sub-Healthy", value: 2 },
		{ label: "Sick", value: 3 },
		{ label: "Serious Sick", value: 4 },
		{ label: "Normal", value: 5 },
		{ label: "Good", value: 6 }
	];
	const bottomFormSchema: FormSchema[] = [
		{
			label: t("felix_ui.spc_cardiovascular"),
			field: "spcCardiovascular",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcCardiovascularRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_respiratory"),
			field: "spcRespiratory",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcRespiratoryRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_digestive"),
			field: "spcDigestive",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcDigestiveRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_renal"),
			field: "spcRenal",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcRenalRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_nervous"),
			field: "spcNervous",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcNervousRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_psychiatric"),
			field: "spcPsychiatric",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcPsychiatricRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_endocrine"),
			field: "spcEndocrine",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcEndocrineRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_metabolic"),
			field: "spcMetabolic",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcMetabolicRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.spc_other"),
			field: "spcOther",
			component: "Select",
			colProps: { span: 8 },
			componentProps: {
				options: examinationOptions
			}
		},
		{
			field: "spcOtherRemark",
			component: "Input",
			colProps: { span: 16 }
		},
		{
			label: t("felix_ui.health_classification"),
			field: "doctorRemark",
			component: "Select",
			componentProps: {
				options: healthyOptions
			},
			colProps: { span: 12 }
		},
		{
			label: t("felix_ui.doctor"),
			field: "doctorId",
			component: "Input",
			colProps: { span: 12 }
		}
	];
	const [bottomForm, { getFieldsValue: getFieldsValue1, setFieldsValue: setFieldsValue1 }] = useForm({
		labelWidth: 150,
		schemas: bottomFormSchema
	});
	const handleTree: TreeProps["onSelect"] = (treeKeys, info) => {
		console.log("selected", treeKeys, info);
	};
	// 时间戳转成时分秒
	function timestampToDate(timestamp: any) {
		const date = new Date(timestamp); // 如果timestamp是数字，直接使用；如果是字符串，确保是数字字符串
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月份是从0开始的
		const day = date.getDate().toString().padStart(2, "0");
		return `${year}-${month}-${day}`;
	}
	const basicInfoSuccess = (val: any) => {
		// requestTest("0db6d702dbf79b09aad99ee0de8a18f0");
		// console.log(val);
		val ? requestTest(val.patientId) : null;
	};
	// 保存
	const handleSubmitRegistration = async () => {
		try {
			saveList.services = await getFieldsValue1();
			saveList.patientId = userList.patientId;
			saveList.patCardno = userList.patCardno;
			saveList.services.examId = userList.services.examId;
			await healthCheckPatientUpdate(saveList).then(res => {
				if (res.code === 0) {
					message.success(t("common.saveSuccessText"));
				} else {
					message.error(res.msg);
				}
			});
		} catch (err) {
			console.log(err);
		}
	};
	// 子组件btn函数
	const handlerToolbarAction = (key: string) => {
		switch (key) {
			case "save":
				handleSubmitRegistration();
				break;
		}
	};
	// 一进来就触发的函数
	let requestTest = async (patientId: string) => {
		await healthCheckPatientGet(patientId).then(res => {
			const mergedObj2 = { ...res, ...res.patientCond };
			const mergedObj3 = {
				...mergedObj2,
				createdTime: timestampToDate(res.patientCond.createdTime),
				status: mergedObj2.status == "2" ? true : false,
				chrAlcohol: mergedObj2.chrAlcohol == "1" ? true : false,
				chrTobacco: mergedObj2.chrTobacco == "1" ? true : false
			};
			setUserList(mergedObj3);
			setFieldsValue1(mergedObj3.services);
			let {
				spcCardiovascularRoom,
				spcDigestiveRoom,
				spcEndocrineRoom,
				spcMetabolicRoom,
				spcMusculoskeletalRoom,
				spcNervousRoom,
				spcOtherRoom,
				spcPsychiatricRoom,
				spcRenalRoom,
				spcRespiratoryRoom
			} = res.services;
			setSreeData([
				{
					title: t("felix_ui.spc_exam"),
					key: "0-0",
					children: [
						{
							title: spcCardiovascularRoom,
							key: "0-0-0"
						},
						{
							title: spcDigestiveRoom,
							key: "0-0-1"
						},
						{
							title: spcEndocrineRoom,
							key: "0-0-2"
						},
						{
							title: spcMetabolicRoom,
							key: "0-0-3"
						},
						{
							title: spcMusculoskeletalRoom,
							key: "0-0-4"
						},
						{
							title: spcNervousRoom,
							key: "0-0-5"
						},
						{
							title: spcOtherRoom,
							key: "0-0-6"
						},
						{
							title: spcPsychiatricRoom,
							key: "0-0-7"
						},
						{
							title: spcRenalRoom,
							key: "0-0-8"
						},
						{
							title: spcRespiratoryRoom,
							key: "0-0-9"
						}
					]
				}
			]);
		});
	};
	return (
		<div className="general_health page">
			<div className="general_health_content">
				<div className="modules_top block">
					<PatientInformation successFn={basicInfoSuccess} />
				</div>
				<div className="flex space-between modules_bottom">
					<div className="modules_left block">
						<div className="block-label">Ⅱ.{t("felix_ui.administration")}</div>
						<Tree
							showLine
							defaultExpandParent={true}
							switcherIcon={<Icon icon={IconEnum.ARROW_DOWN} />}
							onSelect={handleTree}
							treeData={treeData}
						/>
					</div>
					<div className="modules_right block">
						<div className="block">
							<div className="block-label">Ⅲ.{t("felix_ui.administration")}</div>
							<BasicTable register={leftTable}></BasicTable>
						</div>
						<div className="block felx-1">
							<div className="block-label">Ⅳ.{t("felix_ui.administration")}</div>
							<div className="font-bold pl-4">1.{t("felix_ui.internal_medicine")}</div>
							<BasicForm register={bottomForm}></BasicForm>
						</div>
					</div>
				</div>
			</div>
			<Toolbar btnList={["save"]} action={handlerToolbarAction} />
		</div>
	);
}
